package com.white.webserver.service.impl;

import com.white.webserver.WebServerApplication;
import com.white.webserver.service.IMailService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;

import javax.mail.internet.MimeMessage;

@Service
public class MailServiceImpl implements IMailService
{

    @Autowired
    private JavaMailSender mailSender;

    //邮件发件人
    @Value("${spring.mail.username}")
    private String from;

    @Autowired
    TemplateEngine templateEngine;

    @Override
    public void sendEmail(String to, String subject, String verifyCode) {
        Logger logger = LoggerFactory.getLogger(WebServerApplication.class);
        try {
            //创建邮件正文
            Context context = new Context();
            context.setVariable("verifyCode", verifyCode);
            context.setVariable("user", to);

            //将模块引擎内容解析成html字符串
            String emailContent = templateEngine.process("emailTemplate", context);

            MimeMessage message = mailSender.createMimeMessage();
            MimeMessageHelper helper = new MimeMessageHelper(message, true);
            helper.setFrom(from);
            helper.setTo(to);
            helper.setSubject(subject);
            helper.setText(emailContent, true);

            mailSender.send(message);
            logger.info("邮件已经发送。");
        } catch (Exception e) {
            logger.error("发送邮件时发生异常！", e);
        }
    }

}